//
//  JCWVerisonUpdateAlertView.swift
//  HengYouCai
//
//  Created by wll on 2017/11/13.
//  Copyright © 2017年 lwj. All rights reserved.
//  版本更新提示框--代码


private let viewW: CGFloat = 270


import UIKit
import StoreKit


class JCWVerisonUpdateAlertView: UIView {
    
    
    deinit {
        debugPrint("JCWVerisonUpdateAlertView  dealloc")
    }
    
    ///版本号
    private var versionCode: String = ""
    ///更新内容
    private var updateContent: String = ""
    ///是否强制
    private var canCancel: Bool = false
    ///更新链接
    private var updateUrl: String = ""
    ///网页链接
    private var wapLink: String = ""
    ///是否不跳网页
    private var wapStatus : Bool = true

    
    ///版本号 更新内容 是否强制 0强制 1 非强制 // 备用链接
    //resultMap.put("wapLink", CommonConstants.FRONT_SERVER);
    // 备用链接状态
    //resultMap.put("wapStatus", true);
    @discardableResult init(versionCode: String, updateContent: String, canCancel: Bool,  updateUrl: String,  wapLink: String, wapStatus: Bool) {
        
        super.init(frame: UIScreen.main.bounds)
        self.backgroundColor = UIColor.black.withAlphaComponent(0.65)
        JCWShareApplication.delegate?.window??.addSubview(self)
        self.versionCode = versionCode
        self.updateContent = updateContent
        self.canCancel = canCancel
        self.updateUrl = updateUrl
        self.wapLink = wapLink
        self.wapStatus = wapStatus
        //不让点击 直接跳
//            if !wapStatus {
//                guard let webVC = BannerWebViewVC(urlStr: self.wapLink + "?mixApp", title: "") else {return}
//                let web = UIWebView()
//                var userAgent: String = web.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? ""
//                if userAgent.contains("ios/zy") {
//                    debugPrint("userAgent00>>>\(userAgent)")
//                    userAgent.removeSubrange(userAgent.range(of: "ios/zy")!)
//                    debugPrint("userAgent11>>>\(userAgent)")
//                    UserDefaults.standard.register(defaults: ["UserAgent":userAgent])
//                    UserDefaults.standard.synchronize()
//                }
//                self.window?.topMostWindowController?.present(webVC, animated: true, completion: {
//                    self.removeFromSuperview()
//                    return
//                })
//        }
        
        self.createCV()
        
    }
    @discardableResult init(versionCode: String, updateContent: String, canCancel: Bool,  updateUrl: String) {
        
        super.init(frame: UIScreen.main.bounds)
        self.backgroundColor = UIColor.black.withAlphaComponent(0.65)
        JCWShareApplication.delegate?.window??.addSubview(self)
        self.versionCode = versionCode
        self.updateContent = updateContent
        self.canCancel = canCancel
        self.updateUrl = updateUrl
        //不让点击 直接跳
        //            if !wapStatus {
        //                guard let webVC = BannerWebViewVC(urlStr: self.wapLink + "?mixApp", title: "") else {return}
        //                let web = UIWebView()
        //                var userAgent: String = web.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? ""
        //                if userAgent.contains("ios/zy") {
        //                    debugPrint("userAgent00>>>\(userAgent)")
        //                    userAgent.removeSubrange(userAgent.range(of: "ios/zy")!)
        //                    debugPrint("userAgent11>>>\(userAgent)")
        //                    UserDefaults.standard.register(defaults: ["UserAgent":userAgent])
        //                    UserDefaults.standard.synchronize()
        //                }
        //                self.window?.topMostWindowController?.present(webVC, animated: true, completion: {
        //                    self.removeFromSuperview()
        //                    return
        //                })
        //        }
        
        self.createCV()
        
    }
//    ///因为SB审核可能会延迟出现更新的版本信息 所以遇到这种情况就跳转网页
//    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
//        if !wapStatus {
//            guard let webVC = BannerWebViewVC(urlStr: self.wapLink + "?mixApp", title: "") else {return UIView()}
//            let web = UIWebView()
//            var userAgent: String = web.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? ""
//            if userAgent.contains("ios/zy") {
//                debugPrint("userAgent00>>>\(userAgent)")
//                userAgent.removeSubrange(userAgent.range(of: "ios/zy")!)
//                debugPrint("userAgent11>>>\(userAgent)")
//                UserDefaults.standard.register(defaults: ["UserAgent":userAgent])
//                UserDefaults.standard.synchronize()
//
//            }
////            self.window?.topMostWindowController?.present(webVC, animated: true, completion: {
////                self.removeFromSuperview()
////            })
//            MainTabBarViewController.obtainTopViewController()?.present(webVC, animated: true
//                , completion: {
//                    self.removeFromSuperview()
//            })
//
//            return UIView()
//        }else{
//            return super.hitTest(point, with: event)
//        }
//    }
    private func createCV() {
    
        self.addSubview(self.footerV)
        _ = self.footerV.sd_layout().bottomSpaceToView(self,171.ah_wl)?.widthIs(viewW)?.heightIs(200)?.centerXEqualToView(self)
        self.footerV.wl_clipCorner([.bottomLeft, .bottomRight], 10)

        
        self.footerV.addSubview(self.updateBtn)
        _ = self.updateBtn.sd_layout().bottomSpaceToView(self.footerV,33)?.heightIs(38)?.centerXEqualToView(self.footerV)?.leftSpaceToView(self.footerV,25.aw_wl)?.rightSpaceToView(self.footerV,25.aw_wl)
        
        
        self.footerV.addSubview(self.versionCodeLab)
        self.versionCodeLab.text = "新版本号：V\(self.versionCode)"
        _ = self.versionCodeLab.sd_layout().topSpaceToView(self.footerV,6)?.autoHeightRatio(0)?.centerXEqualToView(self.footerV)?.leftSpaceToView(self.footerV,35.aw_wl)?.rightSpaceToView(self.footerV,35.aw_wl)
        
        self.footerV.addSubview(self.updateContentTV)
        self.updateContentTV.text = self.updateContent
        _ = self.updateContentTV.sd_layout().bottomSpaceToView(self.updateBtn,13)?.centerXEqualToView(self.footerV)?.topSpaceToView(self.versionCodeLab,6)?.leftEqualToView(self.versionCodeLab)?.rightSpaceToView(self.footerV,35.aw_wl)
        
        self.addSubview(self.blankView)
        _ = self.blankView.sd_layout()?.widthIs(viewW)?.heightIs(110)?.bottomSpaceToView(self.footerV, 0)?.centerXEqualToView(self.footerV)
        self.addSubview(self.headerImageV)
        _ = self.headerImageV.sd_layout().widthIs(viewW)?.heightIs(180)?.bottomSpaceToView(self.footerV,0)?.centerXEqualToView(self.footerV)
        
        self.addSubview(self.cancleBtn)
        _ = self.cancleBtn.sd_layout().topSpaceToView(self.headerImageV,-self.headerImageV.height_sd/1.4)?.leftSpaceToView(self.headerImageV,-42)?.widthIs(30)?.heightIs(70)
        self.cancleBtn.isHidden = self.canCancel
    }
    //MARK:点击事件
    ///移除
    func removeClose() -> Void {
        self.removeFromSuperview()
    }
    ///跳转更新
    func updateClick() -> Void {
//        self.appInUpdate()
        if let url = URL(string: self.updateUrl) {
            JCWShareApplication.openURL(url)
        }else{
            self.removeFromSuperview()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    ///取消按钮
    let cancleBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setImage(UIImage(named: "home_close"), for: .normal)
        temp.addTarget(self, action: #selector(removeClose), for: .touchUpInside)
        return temp
    }()
    /// 空白背景
    let blankView: UIView = {
        let temp = UIView()
        temp.backgroundColor = UIColor.white
        return temp
    }()
    ///火箭图片
    let headerImageV: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "home_version"))
        temp.isUserInteractionEnabled = true
//        temp.backgroundColor = UIColor.white
        temp.contentMode = .scaleAspectFit
        return temp
    }()
    ///版本号
    let versionCodeLab: UILabel = {
        let temp = UILabel()
        temp.textColor = Normal_333Color
        temp.font = Font_WL(14)
        return temp
    }()
    ///版本更新内容
    let updateContentTV: UITextView = {
        let temp = UITextView()
        temp.textColor = Normal_666Color
        temp.font = Font_WL(13)
        temp.isSelectable = false
        temp.isEditable = false
        temp.textContainerInset = UIEdgeInsetsMake(0, -5, 0, -5)
        return temp
    }()
    
    ///尾部视图
    let footerV: UIView = {
        let temp = UIView()
        temp.backgroundColor = UIColor.white
        return temp
    }()
    
    ///立即更新按钮
    let updateBtn: UIButton = {
        let temp = UIButton(type: .custom)
//        temp.setBackgroundImage(UIImage(named: "versionupdate_btn"), for: .normal)
        temp.backgroundColor = Normal_ThemeColor
        temp.setTitle("立即更新", for: .normal)
        temp.titleLabel?.font = Font_WL(14)
        temp.addTarget(self, action: #selector(updateClick), for: .touchUpInside)
        return temp
    }()
    
}


//MARK:应用内更新
//extension JCWVerisonUpdateAlertView: SKStoreProductViewControllerDelegate {
//
//    ///应用内更新
//    fileprivate func appInUpdate() {
//        let storeProductVC = SKStoreProductViewController()
//        storeProductVC.delegate = self
//        storeProductVC.loadProduct(withParameters: [SKStoreProductParameterITunesItemIdentifier:JCWAPPID]) { (result, error) in
//            if result {
//                JCWShareApplication.keyWindow?.rootViewController?.present(storeProductVC, animated: true, completion: {
//print("谈谈谈")
//                })
//            }else{
//print("false")
//            }
//        }
//    }
//}

